import type { Ref } from 'vue'
import { storeToRefs } from 'pinia'
import { pinia } from '~/stores'
import { useTokenStore } from '~@/stores/token'

export { STORAGE_AUTHORIZE_KEY } from '~@/stores/token'

// HTTP 请求头中使用的授权字段名称，保持标准不变
export const AUTH_HEADER_KEY = 'Authorization'

export function useAuthorization(): Ref<string | null> {
  const store = useTokenStore(pinia)
  const { token } = storeToRefs(store)
  return token
}

export function setAuthorization(token: string | null) {
  const store = useTokenStore(pinia)
  store.setToken(token ?? null)
}

export function clearAuthorization() {
  const store = useTokenStore(pinia)
  store.removeToken()
}

export function decodeJwtPayload(token: string): any | null {
  try {
    const parts = token.split('.')
    if (parts.length !== 3)
      return null
    // atob for base64url
    const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/')
    const json = decodeURIComponent(
      atob(base64)
        .split('')
        .map(c => `%${(`00${c.charCodeAt(0).toString(16)}`).slice(-2)}`)
        .join(''),
    )
    return JSON.parse(json)
  }
  catch {
    return null
  }
}

export function isAuthorizationExpired(token: string | null): boolean {
  if (!token)
    return true
  const payload = decodeJwtPayload(token)
  if (!payload || typeof payload.exp !== 'number')
    return false
  const nowSeconds = Math.floor(Date.now() / 1000)
  return payload.exp <= nowSeconds
}
